﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.IO;
using System.Text;
using FXC.SL.CS.Util;
using Telerik.Windows.Controls;
using System.ServiceModel;
using System.ServiceModel.Channels;
using FXC.SL.CS.ViewModal;
using FXC.Web.Service;
using FXC.Web.Entity;
using System.ServiceModel.DomainServices.Client;
using System.Windows.Browser;
using Telerik.Windows;
using System.Windows.Media.Imaging;
using FXC.SL.CS.ChartUtil;
using FXC.SL.UserControls.FXCChart;
using FXC.SL.Interface;
using FXC.SL.CS.Modal;

namespace FXC.SL
{
    public partial class MainPage : UserControl
    {
        FXSystemContext _contex = App.Current.Resources["FXSystemContext"] as FXSystemContext;

        #region Properties
        private UserStatus _applicationUserStatus;
        public UserStatus ApplicationUserStatus
        {
            get { return _applicationUserStatus; }
            set
            {
                if (value == UserStatus.Login)
                {
                    ucUserLogin.Visibility = System.Windows.Visibility.Visible;
                    rmiLogin.Visibility = System.Windows.Visibility.Collapsed;
                }
                else
                {
                    App.CurrentLoginUser = null;
                    ucUserLogin.Visibility = System.Windows.Visibility.Collapsed;
                    rmiLogin.Visibility = System.Windows.Visibility.Visible;
                }
                _applicationUserStatus = value;
            }
        }
        #endregion

        #region 初始化数据操作

        public MainPage()
        {
            InitializeComponent();
        }

        void UpdateChartTypeMenu(ChartType ct)
        {
            switch (ct)
            {
                case ChartType.CandleStick:
                    rmiStick.IsChecked = false;
                    rmiLine.IsChecked = false;
                    rmiStick.IsEnabled = true;
                    rmiLine.IsEnabled = true;
                    rmiCandleStick.IsEnabled = false;
                    rmiCandleStick.IsChecked = true;
                    break;
                case ChartType.Stick:
                    rmiCandleStick.IsChecked = false;
                    rmiLine.IsChecked = false;
                    rmiLine.IsEnabled = true;
                    rmiCandleStick.IsEnabled = true;
                    rmiStick.IsEnabled = false;
                    rmiStick.IsChecked = true;
                    
                    break;
                default:
                    rmiCandleStick.IsChecked = false;
                    rmiStick.IsChecked = false;
                    rmiStick.IsEnabled = true;
                    rmiCandleStick.IsEnabled = true;
                    rmiLine.IsEnabled = false;
                    rmiLine.IsChecked = true;
                    break;
            }
        }

        void ActiveChart_OnShowVolumeChanged(object sender, IsShowVolumeChangeEventArgs e)
        {
            rmiIsShowVolume.IsChecked = !e.isShowVolue;
        }

        void LoadPrimaryData()
        {
            //_contex.Load(_contex.GetCountryQuery(), delegate(LoadOperation<Country> lc)
            //{
            //},null);
            _contex.Load(_contex.GetCountryQuery());
            _contex.Load(_contex.GetFXCatagoryQuery(), delegate(LoadOperation<FXCatagory> gSR) {
                LoadFXProducts();
            }, null);
        }

        // Initial FXProducts
        void LoadFXProducts()
        {
            _contex.Load(_contex.GetFXProductQuery(), delegate(LoadOperation<FXProduct> gSR)
            {
                // only insert the most useful products
                RadMenuItem rmi = null;
                var query = _contex.FXProducts.Where(p => p.IsImportant == true);
                foreach (FXProduct product in query)
                {
                    // add the item for main menu
                    rmi = new RadMenuItem();
                    rmi.Header = product.FXProductCode;
                    rmi.Click += rmiNewChart_Click;
                    rmiNewProduct.Items.Add(rmi);

                    // add the item for Toolbar
                    rmi = new RadMenuItem();
                    rmi.Header = product.FXProductCode;
                    rmi.Click += rmiNewChart_Click;
                    rmiNewProduct1.Items.Add(rmi);
                }

                // insert seperator
                rmi = new RadMenuItem();
                rmi.IsSeparator = true;
                rmiNewProduct.Items.Add(rmi);
                //
                rmi = new RadMenuItem();
                rmi.IsSeparator = true;
                rmiNewProduct1.Items.Add(rmi);

                // inser grouped menus
                var querycategory = _contex.FXCatagories.Where(c => c.IsPopular == true);
                foreach (FXC.Web.Entity.FXCatagory c in querycategory)
                {
                    rmi = new RadMenuItem();
                    rmi.Header = c.CatagoryName;

                    RadMenuItem rmi1 = new RadMenuItem();
                    rmi1.Header = c.CatagoryName;

                    var subItems = _contex.FXProducts.Where(p => p.FXCatagoryID == c.ID);
                    foreach (FXProduct p in subItems)
                    {
                        RadMenuItem subRmi = new RadMenuItem();
                        subRmi.Header = p.FXProductCode;
                        subRmi.Click += rmiNewChart_Click;
                        rmi.Items.Add(subRmi);
                        //
                        RadMenuItem subRmi1 = new RadMenuItem();
                        subRmi1.Header = p.FXProductCode;
                        subRmi1.Click += rmiNewChart_Click;
                        rmi1.Items.Add(subRmi1);
                    }
                    rmiNewProduct.Items.Add(rmi);
                    rmiNewProduct1.Items.Add(rmi1);
                }
            }, null);
        }

        void InitWindowEvents()
        {
            ucwLogin.Closed += (o, e) =>
            {
                if (ucwLogin.DialogResult == true)
                {
                    ucUserLogin.DataContext = App.CurrentLoginUser;
                    ApplicationUserStatus = UserStatus.Login;
                }
            };
        }

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            FXProductChartManager.SelectionChanged += new EventHandler<SelectedFXVChartEventArgs>(FXProductChartManager_SelectionChanged);

            //初始化Windows Events
            InitWindowEvents();
            // 初始化基础数据
            LoadPrimaryData();
            //获取实时数据
            instantMarketQuoteGrid.Start();

            string settingXML = IsolatedStorageManager.GetStringValue(Constants.DockPanelSetting);
            if (!string.IsNullOrEmpty(settingXML))
                LoadLayoutFromString(settingXML);

            LoadFXData();
        }

        void FXProductChartManager_SelectionChanged(object sender, SelectedFXVChartEventArgs e)
        {
            //System.Diagnostics.Debug.WriteLine("test" + DateTime.Now.ToString());
            UpdateMainPageUI(e.SelectedFXVChart);
        }

        public void UpdateMainPageUI(IChart fxvChart)
        {
            if (fxvChart == null)
                return;

            // Update Tool Bar Chart Period Type
            for (int i = 0; i < mainToolBar5.Items.Count; i++)
            {
                RadToggleButton rtb = mainToolBar5.Items[i] as RadToggleButton;
                if (fxvChart.PeriodType.ToString().Substring(2) == rtb.Tag.ToString())
                    rtb.IsChecked = true;
                else
                    rtb.IsChecked = false;
            }

            // Update Top Menu For Chart Type
            UpdateChartTypeMenu(fxvChart.ChartType);
        }
        #endregion

        #region 保存界面设置相关
        public void SaveLayoutAsString()
        {
            MemoryStream stream = new MemoryStream();
            radDocking1.SaveLayout(stream);
            stream.Seek(0, SeekOrigin.Begin);
            StreamReader reader = new StreamReader(stream);
            IsolatedStorageManager.Save(Constants.DockPanelSetting, reader.ReadToEnd());
        }

        private void LoadLayoutFromString(string xml)
        {
            using (Stream stream = new MemoryStream(Encoding.UTF8.GetBytes(xml)))
            {
                stream.Seek(0, SeekOrigin.Begin);
                radDocking1.LoadLayout(stream);
            }
        }
        #endregion

        #region 菜单按钮事件
        // 新增图表菜单事件
        private void rmiNewChart_Click(object sender, RadRoutedEventArgs e)
        {
            CreateNewChart(((RadMenuItem)sender).Header.ToString());
        }

        // 保存图表数据
        private void rimSaveData_Click(object sender, RadRoutedEventArgs e)
        {
            if (FXProductChartManager.SelectedChart == null)
            {
                MessageBox.Show("请先选择要保存的图表！");
                return;
            }
            FXProductChartManager.SelectedChart.SaveData();
        }

        // 保存为图片
        private void rimSaveImg_Click(object sender, RadRoutedEventArgs e)
        {
            if (FXProductChartManager.SelectedChart == null)
            {
                MessageBox.Show("请先选择要保存的图表！");
                return;
            }
            FXProductChartManager.SelectedChart.SaveToImage();
        }

        private void rmiIsShowVolume_Click(object sender, RadRoutedEventArgs e)
        {
            if (FXProductChartManager.SelectedChart == null)
            {
                MessageBox.Show("请先选择要保存的图表！");
                return;
            }
            FXProductChartManager.SelectedChart.IsShowVolume = !rmiIsShowVolume.IsChecked;

        }

        private void rmiFullScreen_Click(object sender, RadRoutedEventArgs e)
        {
            Application.Current.Host.Content.IsFullScreen = !Application.Current.Host.Content.IsFullScreen;
        }

        // 改变图表类型
        private void rmiChartType_Click(object sender, RadRoutedEventArgs e)
        {
            if (FXProductChartManager.SelectedChart == null)
            {
                MessageBox.Show("请先选择要改变的图表！");
                e.Handled = true;
                return;
            }
            if (sender == rmiCandleStick)
                FXProductChartManager.SelectedChart.ChartType = ChartType.CandleStick;
            else if (sender == rmiStick)
                FXProductChartManager.SelectedChart.ChartType=ChartType.Stick;
            else
                FXProductChartManager.SelectedChart.ChartType=ChartType.Line;
        }

        private void rmiChartTypes_SubmenuClosed(object sender, RadRoutedEventArgs e)
        {
            UpdateChartTypeMenu(FXProductChartManager.SelectedChart.ChartType);
        }

        private void rmReset_Click(object sender, Telerik.Windows.RadRoutedEventArgs e)
        {
            if(MessageBox.Show("重置后请重新打开程序才能生效,是否重置？","FXC", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
                IsolatedStorageManager.Delete(Constants.DockPanelSetting);
        }

        private void rmSaveDockingStatus_Click(object sender, Telerik.Windows.RadRoutedEventArgs e)
        {
            SaveLayoutAsString();
        }

        private void rmiDataWindow_Click(object sender, Telerik.Windows.RadRoutedEventArgs e)
        {
            rpDataWindow.IsHidden = !rpDataWindow.IsHidden;
        }

        private void btnM1_Click(object sender, RoutedEventArgs e)
        {
            
        }

        private void btnToggelTime_Click(object sender, RoutedEventArgs e)
        {
            for (int i = 0; i < mainToolBar5.Items.Count; i++)
            {
                RadToggleButton rtb = mainToolBar5.Items[i] as RadToggleButton;
                if (rtb != null)
                {
                    if (rtb != sender)
                        rtb.IsChecked = false;
                    else
                    {
                        rtb.IsChecked = true;
                        switch(rtb.Tag.ToString())
                        {
                            case "1M":
                                FXProductChartManager.SelectedChart.PeriodType = PeriodType.T_1M;
                                break;
                            case "5M":
                                FXProductChartManager.SelectedChart.PeriodType = PeriodType.T_5M;
                                break;
                            case "15M":
                                FXProductChartManager.SelectedChart.PeriodType = PeriodType.T_15M;
                                break;
                            case "30M":
                                FXProductChartManager.SelectedChart.PeriodType = PeriodType.T_30M;
                                break;
                            case "1H":
                                FXProductChartManager.SelectedChart.PeriodType = PeriodType.T_1H;
                                break;
                            case "4H":
                                FXProductChartManager.SelectedChart.PeriodType = PeriodType.T_4H;
                                break;
                            case "1D":
                                FXProductChartManager.SelectedChart.PeriodType = PeriodType.T_1D;
                                break;
                            case "1W":
                                FXProductChartManager.SelectedChart.PeriodType = PeriodType.T_1W;
                                break;
                            case "1MN":
                                FXProductChartManager.SelectedChart.PeriodType = PeriodType.T_1MN;
                                break;
                            default:
                                break;
                        }

                    }
                }
            }
        }

        private void rmiAddUser_Click(object sender, Telerik.Windows.RadRoutedEventArgs e)
        {
            ucwAdduser.ShowDialog();
        }

        private void rmiLogin_Click(object sender, Telerik.Windows.RadRoutedEventArgs e)
        {
            ucwLogin.ShowDialog();
        }

        #endregion

        #region 其他控件事件
        private void radDocking1_Close(object sender, Telerik.Windows.Controls.Docking.StateChangeEventArgs e)
        {
            for (int i = 0; i < e.Panes.Count(); i++)
            {
                FXProductChartManager.RemoveChart(e.Panes.ElementAt(i).Content as IChart);
            }
        }
        #endregion

        #region Public Method
        public void CreateNewChart(string productName)
        {
            IChart nchart = FXC.SL.CS.ChartUtil.FXProductChartManager.AddChart(RPG1, productName);
            rddbNewchart.IsOpen = false;
            if (nchart != null)
            {
                //nchart.OnChartTypeChanged += new EventHandler<ChartTypeChangeEventArgs>(ActiveChart_OnChartTypeChanged);
                nchart.OnShowVolumeChanged += new EventHandler<IsShowVolumeChangeEventArgs>(ActiveChart_OnShowVolumeChanged);
                nchart.OnMouseMove += new EventHandler<ChartMouseMoveEventArgs>(ActiveChart_OnMouseMove);
            }
        }
        #endregion

        void LoadFXData()
        {
            //FXC.SL.CS.ChartUtil.ChartManager.AddChart(RPG1, "EURAUD");
            IChart nchart = FXC.SL.CS.ChartUtil.FXProductChartManager.AddChart(RPG1, "USDCHF");
            if (nchart != null)
            {
                //nchart.OnChartTypeChanged += new EventHandler<ChartTypeChangeEventArgs>(ActiveChart_OnChartTypeChanged);
                nchart.OnShowVolumeChanged+=new EventHandler<IsShowVolumeChangeEventArgs>(ActiveChart_OnShowVolumeChanged);
                nchart.OnMouseMove += new EventHandler<ChartMouseMoveEventArgs>(ActiveChart_OnMouseMove);
            }
            //proxy.GetFXCDataCompleted += (o, e) =>
            //    {
            //        if (e.Error == null)
            //        {
            //            fxpChart1.LoadData(e.Result.Take(30).ToList());
            //        }
            //        else
            //        {
            //        }
            //    };
            //proxy.GetFXCDataAsync("EURAUD", "30M");
        }

        void ActiveChart_OnMouseMove(object sender, ChartMouseMoveEventArgs e)
        {
            DataWindowViewModal vm = App.Current.Resources["DataWindowViewModal"] as DataWindowViewModal;
            //vm.Data.DateTimeData = e.CurrentData.ProcessDateTime;
            //vm.Data.Open = e.CurrentData.OpenPrice;
            //vm.Data.Close = e.CurrentData.ClosePrice;
            //vm.Data.High = e.CurrentData.HighPrice;
            //vm.Data.Low = e.CurrentData.LowPrice;
            //vm.Data.Volume = e.CurrentData.Volume;
            vm.Update(e.CurrentData);
        }

        private void btnZoomBig_Click(object sender, RoutedEventArgs e)
        {
            IChart activeChart = FXProductChartManager.SelectedChart;
            if (activeChart != null)
            {
                activeChart.ChangeZoomBig();
            }
        }

        private void btnZoomSmall_Click(object sender, RoutedEventArgs e)
        {
            IChart activeChart = FXProductChartManager.SelectedChart;
            if (activeChart != null)
            {
                activeChart.ChangeZoomSmall();
            }
        }

        

        
        
    }
}
